<?php

namespace app\common\model\operatingaccount;

use app\api\controller\Pub;
use app\common\model\user\User;
use app\common\model\company\Company;
use think\Model;


class Accountin extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'operating_account_in_warehouse';
    protected $pk    = 'Id';

    /**
     * 创建企业信息
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_create($data)
    {
        $Accountin = new Accountin;
        //创建时间
        $info['AccountTime'] = date('Y-m-d H:i:s', time());
        $info['OrderListId'] = $data['HawaListId'];
        //库管数据
        $warehouse = User::get($data['receipt']['WarehouseId']);
        $info['InWarehouseUserId'] = $data['receipt']['WarehouseId'];
        $info['InWarehouseUserName'] = $warehouse->Name;
        //司机
        $info['TransportUserName'] = $data['TransitDrvierName'];
        //产废单位
        $company =  Company::get($data['CompanyId']);
        $info['HawaCompanyName'] = $company->Name;
        $info['HawaCompanyId'] = $data['CompanyId'];
        $info['OrderListId'] = $data['HawaListId'];
        $info['TransportCarCode'] = $data['TransitBrandNumber'];
        //危废信息
        foreach ($data['hawa'] as $key => $value) {
            $list[$key] = $info;
            $list[$key]['GoodId']=$value['GoodId'];
            $list[$key]['GoodName']=$value['GoodName'];
            $list[$key]['BatchCode']=$value['LotNumber'];//批次号
            $list[$key]['Quantity'] = $value['Weight'];//数量
            $list[$key]['Unit'] = '公斤';//单位
            $list[$key]['BoxType'] = $value['Box'];
            $list[$key]['BoxCount'] = $value['BoxCount'];
            $list[$key]['StorageCode'] = $value['areainfo']['Name'];
            $list[$key]['StorageType'] = $value['areainfo']['GroupName'];
            //以代码id 查询最后的余量 
            $balance = self::getbalance($value['GoodId'],$value['GoodName']);
            $list[$key]['CodeBalance'] =  $balance['code']+$value['Weight'];
            $list[$key]['NameBalance'] =  $balance['name']+$value['Weight'];
        }
        if(empty($list)){
            return serr('缺少货物数据');
        }
        $Accountin->saveAll($list);
        return sok('添加成功');
    }

    /**
     * 获取此危废的结余量
     * @param  [type] $goodid   [description]
     * @param  [type] $goodname [description]
     * @return [array]           [返回id对应的余量 和name对应的余量]
     */
    public static function getbalance($goodid,$goodname){
        //按id 查询
        $idindata = Accountin::where('GoodId',$goodid)->order('AccountTime desc')->field('AccountTime,GoodId,GoodName,NameBalance,CodeBalance')->find();
        $idoutdata = Accountout::where('GoodId',$goodid)->order('AccountTime desc')->field('AccountTime,GoodId,GoodName,NameBalance,CodeBalance')->find();
        $iddata = ['time'=>'','weight'=>0];
        $namedata = ['time'=>'','weight'=>0];
        if(!empty($idindata['AccountTime'])){
           $iddata['time'] = $idindata['AccountTime'];
           $iddata['weight'] = $idindata['CodeBalance'];
           $iddata['name'] = $idindata['GoodName'];
        }

        if(!empty($idoutdata['AccountTime'])&&$idoutdata['AccountTime']>$iddata['time']){
            $iddata['time'] = $idoutdata['AccountTime'];
            $iddata['weight'] = $idoutdata['CodeBalance'];
            $iddata['name'] = $idoutdata['GoodName'];
        }

        if(!empty($iddata['name'])&&$iddata['name']!==$goodname){
            //按id 和 name查询
            $nameindata = Accountin::where('GoodId',$goodid)->where('GoodName',$goodname)->order('AccountTime desc')->field('AccountTime,NameBalance')->find();
            $nameoutdata = Accountout::where('GoodId',$goodid)->where('GoodName',$goodname)->order('AccountTime desc')->field('AccountTime,NameBalance')->find();
            if(!empty($nameindata['AccountTime'])){
               $namedata['time'] = $nameindata['AccountTime'];
               $namedata['weight'] = $nameindata['CodeBalance'];
               $namedata['name'] = $nameindata['GoodName'];
            }

            if(!empty($nameoutdata['AccountTime'])&&$nameoutdata['AccountTime']>$namedata['time']){
                $namedata['time'] = $nameoutdata['AccountTime'];
                $namedata['weight'] = $nameoutdata['CodeBalance'];
                $namedata['name'] = $nameoutdata['GoodName'];
            }
        }else{
            $namedata['weight'] = $iddata['weight'];
        }
        return ['name'=>$namedata['weight'],'code'=>$iddata['weight']];
    }   
    
    /**
     * 获取信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function user_getinfo($id, $type = 'buss', $hidden = ['OperationLog'])
    {
        $data = Customer::get($id);
        if (empty($data)) {
            return moerr('没有找到您需要的信息');
        }
        $data['list'] = Customervisit::getlist($id);
        //保护期 守卫
        if ($type == 'buss') {
            if ($data->guard_state && $data->BussinessId !== Pub::userid()) {
                if (!CUSTOMER_BIND_SHOW_INFO) {
                    return moerr('该客户处于保护期,无法查看','','goback');
                }
                //保护期客户将隐藏客户的联系方式\其他电话\负责人电话\负责人姓名\备注\图片备注\
                $data['Tel']      = substr($data['Tel'], 0, 2) . '***' . substr($data['Tel'], -3);
                $data['OtherTel'] = [];
                $data['UserName'] = '该客户处于保护期,无法查看';
                $data['UserTel']  = substr($data['Tel'], 0, 2) . '***' . substr($data['Tel'], -3);
                $data['Note']     = '该客户处于保护期,无法查看';
                $data['Img']      = '';
                $data['list']     = [];
            }
        }
        $data['StateText'] = Customer::getStatusText($data['State']);
        $data['StateList'] = Customer::getStatusText();
        $data['ScaleList'] = Customer::distinct(true)->column('Scale');
        $data['TypeList']  = Customer::distinct(true)->column('Type');
        $data->hidden($hidden);
        return $data;
    }

/**
 * 获取订单列表
 * @param  [type] $data    [主数据]
 * @param  string $type    [查询类型/hawa/buss]
 * @param  [type] $is_page [是否分页显示]
 * @return [type]          [description]
 */
    public static function usergetlist($data, $type = 'buss', $is_page = true)
    {
        $rdata = new Customer;
        if ($type == 'buss') {
            // $rdata   = Customer::where('State', Customer::STATEOK);
            $visible = ['CustomerId', 'AddTime', 'CompanyId','Name', 'LastTime', 'Address', 'Lon', 'Lat', 'Type', 'Scale', 'LastTime', 'BussinessId'];
        } else if ($type == 'mana') {
            // $rdata   = Customer::where('State', Customer::STATEOK);
            $rdata   = $rdata->with(['bussinfo']);
            $visible = ['CustomerId', 'AddTime', 'CompanyId','Name', 'LastTime', 'Address', 'Lon', 'Lat', 'Type', 'Scale', 'LastTime', 'BussinessId'];
        } else if($type=='regulatory'){
            $rdata   = $rdata->with(['bussinfo']);
            $visible = ['CustomerId', 'AddTime', 'CompanyId','Name', 'LastTime', 'Address', 'Lon', 'Lat', 'Type', 'Scale', 'LastTime', 'BussinessId'];
        }else {
            return moerr('缺少参数');
        }
        if (!empty($data['field'])) {
            $visible = array_merge($data['field'], $visible);
        }

        $option = come_model_option($data, $rdata, $is_page);

        $rdata = $option['rdata'];
        $data  = $option['data'];

        if (!empty($data['field'])) {
            $rdata = $rdata->field($visible);
        }
        $rdata = $rdata->select();
        if (!empty($visible)) {
            $visible = array_merge(['guard_state'], $visible);
            $rdata = $rdata->visible($visible);
        }

        $ndata['list'] = $rdata->toArray();
        // dump($ndata);
        $ndata['statetext'] = Customer::getStatusText();
        // $goodid = get_array_id($ndata,'GoodId','list','listinfo');
        if ($is_page) {
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        }
        return $ndata;
    }

    /**
     * 用户修改信息
     * @param  [type]  $data   [description]
     * @param  boolean $wtnote [是否记录]
     * @return [type]          [description]
     */
    public static function user_reinfo($data, $wtnote = true)
    {
        if (empty($data['id'])) {
            return moerr('缺少重要参数');
        }
        $info     = Customer::get($data['id']);
        $userinfo = User::getinfo();
        $reinfo   = empty($info->OperationLog) ? '' : $info->OperationLog . "\n";
        $reinfo   = $reinfo . '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $nreinfo  = '';
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if (empty($sb)) {
                continue;
            }
            //取原数据
            if ($key == 'OtherTel') {
                if (is_array($info->$key)) {
                    $ovalue = implode(',', $info->$key);
                } else {
                    $ovalue = $info->$key;
                }
            } else {
                $ovalue = $info->$key;
            }

            if ($key == 'State' && $value !== $ovalue) {
                if ((int) $ovalue !== (int) $value) {
                    $info->$key = $value;
                    //value将改变成文字所以提前赋值
                    $value   = $info->getStatusText((int) $value);
                    $ovalue  = $info->getStatusText((int) $ovalue);
                    $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                }
            } else if ($key == 'isPlanform' ) {
                if ($value !== $ovalue && (int) $ovalue !== (int) $value) {
                    $info->$key = $value;
                    $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                }
            } else if ($key == 'BussinessId' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $value . User::get($value)->Name;
                $ovalue  = $ovalue . User::get($ovalue)->Name;
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            } else if ($key == 'CompanyId' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $value . Company::get($value)->Name;
                $ovalue  = $ovalue . Company::get($ovalue)->Name;
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            } else if (!empty($value) && $ovalue !== $value) {
                $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                $info->$key = $value;
            }
        }
        if (!empty($nreinfo)) {
            if ($wtnote) {
                $reinfo             = $reinfo . "\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        } else {
            return moerr('没有找到需要调整的数据');
        }
    }

    public static function getfiledname($str)
    {
        $filename = [
            'State'           => '状态',
            'CompanyId'       => '企业id',
            'Name'            => '企业名称',
            'Address'         => '企业地址',
            'Lon'             => '经度',
            'Lat'             => '纬度',
            'Tel'             => '联系电话',
            'OtherTel'        => '其他电话',
            'LicenseNumber'   => '信用代码',
            'UserName'        => '负责人姓名',
            'UserTel'         => '负责人电话',
            'Type'            => '企业分类',
            'Scale'           => '产废规模',
            'Note'            => '备注',
            'Img'             => '图片备注',
            'AppointmentTime' => '预约时间',
            'Visitingtime'    => '上门时间',
            'BindTime'        => '绑定时间',
            'BussinessId'     => '业务id',
            'isPlanform'      => '是否接入平台',
        ];
        if (empty($filename[$str])) {
            return false;
        }
        return $filename[$str];
    }

}
